/*
 * Copyright (C) 2025 ameise <ameise.wang@gmail.com> - All Rights Reserved
 *
 * This file is part of e3pool.
 *
 * e3pool is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * e3pool is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with e3pool. If not, see <https://www.gnu.org/licenses/>.
 */

package go_pool

import "gitee.com/ameise84/e3pool/obj_pool"

var _gWorkerGcPool obj_pool.Pool[*worker]

func init() {
	_gWorkerGcPool = obj_pool.NewPool[*worker](func() *worker {
		return &worker{
			c: make(chan *task),
		}
	})
}

func newWorker() *worker {
	w := _gWorkerGcPool.Get()
	w.run()
	return w
}

func releaseWorker(w *worker) {
	_gWorkerGcPool.Put(w)
}

type worker struct {
	c chan *task
}

func (ts *worker) run() {
	go safeFunc(nil, "go worker", ts.loop)
}

func (ts *worker) submit(t *task) {
	ts.c <- t
}

func (ts *worker) loop(...any) {
	for {
		select {
		case t := <-ts.c:
			if t == nil {
				return
			}
			doTask(t)
			putWorker(ts)
		}
	}
}
